//
//  ViewController.swift
//  JKRxSwift
//
//  Created by 王冲 on 2020/8/14.
//  Copyright © 2020 王冲. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    fileprivate var button: UIButton = {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        button.backgroundColor = .brown
        button.tag = 100
        return button
    }()
    
    fileprivate lazy var bag: DisposeBag = DisposeBag()
    
    @IBOutlet weak var textFiled1: UITextField!
    
    @IBOutlet weak var textFiled2: UITextField!
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    
    @IBOutlet weak var scrollView1: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
        button.center = self.view.center
        // button.addTarget(self, action: #selector(click), for: .touchUpInside)
        button.rx.tap.subscribe { (event: Event<()>) in
            print("rx的点击")
        }.disposed(by: bag)
        view.addSubview(button)

//        textFiled1.rx.text.subscribe { (event: Event<String?>) in
//            print("第1个输入框文字：")
//        }.disposed(by: bag)
//        textFiled2.rx.text.subscribe(onNext: { (str: String?) in
//            guard let str = str else {
//                return
//            }
//            print("第2个输入框文字：\(str)")
//        }, onError: { (error) in
//
//        }, onCompleted: {
//
//        }) {
//
//        }.disposed(by: bag)
        // 输入的值绑定到label上
        textFiled1.rx.text.bind(to: label1.rx.text).disposed(by: bag)
        
        /*
        label1.addObserver(self, forKeyPath: "text", options: .new, context: nil)
        label2.addObserver(self, forKeyPath: "text", options: .new, context: nil)
        */
        label1.rx.observe(String.self, "text").subscribe(onNext: { (string: String?) in
            print("rx监听：\(string!)")
        }).disposed(by: bag)
        
        scrollView1.contentSize = CGSize(width: 1000, height: 0)
        scrollView1.rx.contentOffset.subscribe(onNext: { (point: CGPoint) in
            print("偏移量：\(point.x)")
        }).disposed(by: bag)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if label1.isEqual(object) {
            if keyPath == "text" {
                print("\((change?[NSKeyValueChangeKey.newKey])!)")
            }
        } else if label2.isEqual(object) {
            
        }
    }
    
    @objc func click(sender: UIButton) {
        print("按钮点击")
    }


}

